/**
 * 
 */
package com.jrh.web.extend.velocity;

import org.apache.oro.text.perl.MalformedPerl5PatternException;
import org.apache.oro.text.perl.Perl5Util;
import org.apache.velocity.app.event.implement.EscapeHtmlReference;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.util.StringUtils;

/**
 * 类ExtendEscapeHtmlReference.java的实现描述：TODO 类实现描述
 * 
 * @author shengli.caosl 2012-2-25 下午9:41:27
 */
public class ExtendEscapeHtmlReference extends EscapeHtmlReference {

    private Perl5Util       perl          = new Perl5Util();
    private String          unmatchRegExp = null;

    public void setRuntimeServices(RuntimeServices rs) {
        unmatchRegExp = StringUtils.nullTrim(rs.getConfiguration().getString("eventhandler.escape.html.unmatch"));
        if ((unmatchRegExp != null) && (unmatchRegExp.length() == 0)) {
            unmatchRegExp = null;
        }
        if (unmatchRegExp != null) {
            try {
                perl.match(unmatchRegExp, "");
            } catch (MalformedPerl5PatternException E) {
                rs.getLog().error("Invalid regular expression '" + unmatchRegExp + "'.  No escaping will be performed.",
                                  E);
                unmatchRegExp = null;
            }
        }

    }

    public Object referenceInsert(String reference, Object value) {
        if (value == null) {
            return value;
        }
        if (unmatchRegExp == null) {
            return escape(value);
        } else if (!perl.match(unmatchRegExp, reference)) {
            return escape(value);
        } else {
            return value;
        }
    }
}
